<?php
/* new version;
 * update: method insert,update,delete,query_select echo error if not success;
 * add: method set_show_error($yes) config TRUE or FALSE die if all query error and show error;
 */

class Model extends MySQLi
{
    	protected $host = "localhost";
        protected $user = "root";
    	protected $pass = "";
    	protected $db = "pla2com";
        
        var $field;
        var $table;
        var $where;
        var $order;
        var $limit;
        var $show_error = TRUE;
        var $last_query = array();

        function __construct($host = false,$user = false,$pass = false,$db = false){
            if($host == false || $user == false || $pass == false || $db == false){
                parent::__construct($this->host, $this->user, $this->pass, $this->db);                
            }
            else{
                parent::__construct($host, $user, $pass, $db);
            }
            if (mysqli_connect_error()) {
                die('Connect Error (' . mysqli_connect_errno() . ') '
                        . mysqli_connect_error());
            }
            $this->set_charset("utf8");
            $this->set_show_error(TRUE);
        }

        function select_row($table,$where,$field = null){
            if(!empty($field)){
                $result = $this->select()->from($table)->where($where)->query_select();
            }
            else{
                $result = $this->select($field)->from($table)->where($where)->query_select();
            }
            return $result->fetch_assoc();
        }
        
        function select_field($table,$field,$where){
            $result = $this->select($field)->from($table)->where($where)->query_select();
            $row = $result->fetch_row();
            return $row[0];
        }
        
        function get_count_field($table,$where = null){
            if(empty($where)){
                $result = $this->select('COUNT(*) as c')->from($table)->query_select();
                
            }
            else{
                $result = $this->select('COUNT(*) as c')->from($table)->where($where)->query_select();                
            }
            $item = $result->fetch_assoc();
            return $item['c'];
        }
        //ดึงค่า mysqli result ทั้งหมดออกมาเป็นอาเรย์
        public function fetch_assoc_all($result){
            $item = array();
            while($buffer = $result->fetch_assoc()){
                $item[] = $buffer;
            }
            return $item;
        }
        
        //ตั้งค่าว่าจะให้แสดง ERROR ของ mysql หลังจากการ query ผิดพลาดหรือไม่
        public function set_show_error($yes){
            if($yes == TRUE || $yes == FALSE){
                $this->show_error = $yes;                
            }
        }
        // เปลี่ยนค่าสตริงเพื่อใช้กับ MySQL
        public function data_field($str){
            $str = (string)$str;
            if((!preg_match('/\\\+/',$str) && preg_match('/\+/',$str)) ||
               (!preg_match('/\\\-/',$str) && preg_match('/\-/',$str)) ||
               (!strrpos($str,'\*') && preg_match('/\*/',$str))){
                return $str;
            }
            else{
                $str = str_replace(array('\+','\-','\*','\/'),array('+','-','*','/'),$str);
                return "'".$str."'";
            }
        }
        
        public function query($query){
            $this->last_query['query'] = $query;
            $result = $this->real_query($query);
            if($this->show_error == TRUE && !$result){
                die($query."<br />".$this->error);
            }
            else{
                return new Model_result($this);
            }
        }
        
    	public function insert($table,$input){
    		$field = array();
    		$data = array();
    		foreach($input as $key => $value){
    			$field[] .= $key;
    			$data[] .= $this->data_field($value);
    		}
    		$field = implode(',',$field);
    		$data = implode(',',$data);
    		$sql = "INSERT INTO ".$table."({$field}) VALUE({$data})";
                $this->last_query['insert'] = $sql;
                $this->last_query['type'] = 'INSERT';
    		return  $this->query($sql);
    	}
    	public function update($table,$input,$where){
    		$data = array();
    		foreach($input as $key => $value){
    			$data[] .= $key."=".$this->data_field($value);
    		}
    		$data = implode(',',$data);
    		$sql = "UPDATE {$table} SET {$data} WHERE {$where}";
                $this->last_query['update'] = $sql;
                $this->last_query['type'] = 'UPDATE';
    		return  $this->query($sql);
    	}
    	public function delete($table,$where){
    		$sql = "DELETE FROM {$table} WHERE {$where}";
                $this->last_query['delete'] = $query;
                $this->last_query['type'] = 'DELETE';
    		return $this->query($sql);
    	}
    	// select object
    	public function select($input = FALSE){        
    		if(is_array($input)){
    			$this->field = " ".implode(',',$input);
    		}
    		else if(!$input){
    			$this->field = " *";
    		}
    		else {
    			$this->field = " ".$input;
    		}
    		return $this;
    	}
    	public function from($input){
    		$this->table = " FROM ".$input;
    		return $this;
    	}
    	public function where($input){
    		if(!empty($input)){
    			$this->where = " WHERE ".$input;
    		}
    		return $this;
    	}
    	public function order($input){
    		if(!empty($input)){
    			$this->order = " ORDER BY ".$input;
    		}
    		return $this;
    	}
    	public function limit($input){
    		if(!empty($input)){
    			$this->limit = " LIMIT ".$input;
    		}
    		return $this;
    	}
    	public function get_maxfield($table,$field,$where = FALSE){
    		if(empty($where)) $where = "1";
    		$result = $this->select('max('.$field.')')->from($table)->where($where)->query_select();
    		$max_field = $result->fetch_row();
    		return $max_field[0];
    	}
    	public function get_minfield($table,$field,$where = FALSE){		
    		if(empty($where)) $where = "1";
    		$result = $this->select('min('.$field.')')->from($table)->where($where)->query_select();
    		$max_field = $result->fetch_row();
    		return $max_field[0];
    	}
    	public function get_sumfield($table,$field,$where = FALSE){
    		if(empty($where)) $where = "1";
    		$result = $this->select('sum('.$field.')')->from($table)->where($where)->query_select();
    		$max_field = $result->fetch_row();
    		return $max_field[0];
    	}
    	public function query_select(){
    		$sql = "SELECT".$this->field.$this->table.$this->where.$this->order.$this->limit;
    		$this->field = NULL;
    		$this->table = NULL;
    		$this->where = NULL;
    		$this->order = NULL;
    		$this->limit = NULL;
                $this->last_query['type'] = 'SELECT';
    		return $this->query($sql);
    	}
    	// select object
    	function __destruct(){
		$this->close();
	}
}

Class Model_result extends MySQLi_Result{
    public function __construct($obj){
        parent::__construct($obj);
    }
}
